<template>
  <div style="margin-left: 75px">
    <el-radio-group v-model="loginForm.loginType">
      <el-radio :label="1">账号密码登录</el-radio>
      <el-radio :label="2">验证码登录</el-radio>
    </el-radio-group>
  </div>
  <el-form
      :model="loginForm" :rules="rules" ref="loginFormRef" label-width="80px" class="login-form">
    <el-form-item label="账号" prop="username" v-if="loginForm.loginType === 1">
      <el-input v-model="loginForm.username"></el-input>
    </el-form-item>
    <el-form-item label="密码" prop="password" v-if="loginForm.loginType === 1">
      <el-input type="password" v-model="loginForm.password"></el-input>
    </el-form-item>

    <el-form-item label="手机号" prop="phone" v-if="loginForm.loginType === 2">
      <el-input v-model="loginForm.phone" type="text"></el-input>
    </el-form-item>
    <el-form-item label="验证码" prop="code" v-if="loginForm.loginType === 2">
      <el-input type="text" v-model="loginForm.code" style="width: 100px; padding-right: 2px"></el-input>
      <el-button
          type="primary"
          :disabled="isButtonDisabled"
          @click="getCode"
      >
        {{ isButtonDisabled ? `重新发送(${countdown}s)` : '获取验证码' }}
      </el-button>
    </el-form-item>

    <div style="margin-left: 75px">
      <el-form-item>
        <el-button type="primary" @click="submitForm">登录</el-button>
      </el-form-item>
    </div>
  </el-form>
</template>

<script setup>
import {computed, onUnmounted, reactive, ref} from 'vue';
import {ElMessage} from 'element-plus';
import {LoginApi} from '@/apis/api.ts';
import JSEncrypt from 'jsencrypt'
import Config from "@/stores/config.ts";
import Router from "@/router/index.ts";

const loginForm = reactive({
  username: '',
  password: '',
  phone: '',
  code: '',
  loginType: 1 // 默认是用户名密码登录
});

const isButtonDisabled = ref(false);
const countdown = ref(0);
let countdownInterval = ref(null)

const loginFormRef = ref(null);

const pk = Config.publicKey

function getCode() {
  if (isButtonDisabled.value) return; // 如果按钮已禁用，则不执行任何操作

  if (loginForm.loginType !== 2) {
    ElMessage.error('请先选择验证码登录的方式');
    return;
  }
  if (loginForm.phone === '') {
    ElMessage.error('请先输入手机号');
    return;
  }
  alert("1")
  // 禁用按钮并开始倒计时
  isButtonDisabled.value = true;
  countdown.value = 60;
  startCountdown();
}

const startCountdown = () => {
  // 清除之前的倒计时（如果有的话）
  if (countdownInterval) clearInterval(countdownInterval);

  // 开始新的倒计时
  countdownInterval = setInterval(() => {
    if (countdown.value > 0) {
      countdown.value--;
    } else {
      // 倒计时结束，重置按钮状态
      clearInterval(countdownInterval);
      countdownInterval = null;
      isButtonDisabled.value = false;
      countdown.value = 0;
    }
  }, 1000); // 每秒更新一次倒计时
};

// 在组件卸载前清除倒计时
onUnmounted(() => {
  if (countdownInterval) clearInterval(countdownInterval);
});

const rules = computed(() => {
  if (loginForm.loginType === 1) {
    return {
      username: [
        {required: true, message: '请输入账号', trigger: 'blur'},
      ],
      password: [
        {required: true, message: '请输入密码', trigger: 'blur'},
      ],
      // 注意：这里没有code的规则，因为当loginType为1时不需要验证码
    };
  } else if (loginForm.loginType === 2) {
    return {
      phone: [
        {required: true, message: '请输入手机号', trigger: 'blur'},
        {pattern: /^1\d{10}$/, message: '请输入正确的手机号', trigger: 'blur'},
      ],
      code: [
        {required: true, message: '请输入验证码', trigger: ''},
        {min: 6, message: '验证码为6位', trigger: 'blur'},
        {pattern: /^[0-9]*$/, message: '验证码只能为数字', trigger: 'blur'},
      ],
    };
  } else {
    // 可以根据需要添加其他类型的验证规则
    return {};
  }
});

const submitForm = () => {
  loginFormRef.value.validate((valid) => {
    if (valid) {
      let form = {}
      if (loginForm.loginType === 1) {
        // 密码加密
        const crypt = new JSEncrypt()
        crypt.setPublicKey(pk)
        const encryptedPassword = crypt.encrypt(loginForm.password)

        form = {username: loginForm.username, password: encryptedPassword}
      } else {
        form = {phone: loginForm.phone, code: loginForm.code}
      }

      // 获取当前url?后面的路径并跳转
      let currentUrl = window.location.href
      const fromUrl = currentUrl.split('from:')[1]
      console.log('get from url: ' + fromUrl)

      LoginApi(form, 'admin', loginForm.loginType).then((resp) => {
        console.log('登录响应：', resp)
        if (resp.code === 200) {
          // 返回值写localStorage
          const token = resp.data
          localStorage.setItem('satoken', token);
          if (fromUrl) {
            // 重定向到指定url
            window.location.href = fromUrl
          } else {
            Router.push('/')
          }
          ElMessage.success('登录成功');
        } else {
          ElMessage.error(resp.message);
        }
      })
    } else {
      // ElMessage.error('请输入账号/密码');
      return false;
    }
  });
};
</script>

<style scoped>
.login-form {
  width: 300px;
  margin-top: 50px;
}
</style>
